//创建一个服务
//定义一个接口 /api/users
//读取db.json文件 向前端返回数据

require("dotenv").config();
const http = require("http");
const fs = require("fs");
const OpenAI = require("openai");
const openai = new OpenAI({
  baseURL: "https://api.deepseek.com",
  apiKey: process.env.DEEPSEEK_API_KEY,
});

const server = http.createServer(async (req, res) => {
  //处理跨域
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "*");
  res.setHeader("Access-Control-Allow-Methods", "*");

  if (req.url.includes("/api/users")) {
    //接口
    //console.log('接口被调用了')
    const url = new URL(req.url, `http://${req.headers.host}`);
    const query = url.searchParams.get("name");
    //console.log(query,'query')
    if (query == "all") {
      const data = fs.readFileSync("./db.json", "utf-8");
      const users = JSON.parse(data).users;
      //console.log(users)
      res.end(
        JSON.stringify({
          success: true,
          data: users,
        })
      );
    } else {
      //让deepseek去db.json中查找 哪一条数据的name属性值等于query
      //将这条数据返回前端
      const data = fs.readFileSync("./db.json", "utf-8");
      const users = await openai.chat.completions.create({
        messages: [
          { role: "system", content: "你是一个编程高手" },
          {
            role: "user",
            content: `请分析${data}中的数据，找出一条数据的name属性值等于${query}，
            将这条数据读取出来，存放在一个数组中，返回给我，不要任何其他多余的文字，只要形如这样的：
            {
            "data":[{
            "id": 1,
            "name": "廖丽丽",
            "age": "23",
            "address": "南昌"
            }]
           }`,
          },
        ],
        model: "deepseek-chat",
      });
      //console.log(users,'users--')
      console.log(
        users.choices[0].message.content,
        "users.choices[0].message.content--"
      );
      res.end(users.choices[0].message.content);
      //   res.end(
      //     JSON.stringify({
      //       success: true,
      //       data: JSON.parse(users.choices[0].message.content),
      //     })
      //   );
    }
  }
});
server.listen(3000, () => {
  console.log("服务器启动成功");
});
